package dbTools.coeModel.modelElement;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;


import dbTools.coeModel.CodeModel;
import dbTools.coeModel.annotation.FillItem;
import dbTools.tableInfo.info.TableInfo;
import dbTools.util.FileUtil;
import dbTools.util.ReflectionHelper;

public abstract class AbstractReplaceElement extends ModelElement {

	protected FileUtil file;
	
	@Override
	public void writerCode(CodeModel codeModel,TableInfo tableInfo) {
		
		if(isCopySus(codeModel,tableInfo)==false)
		{
			return;
		}
		
		AbstractReplaceElement element=ReflectionHelper.getReflectObj(this.getClass());
		
		Method[] methods=element.getClass().getMethods();

		try {
			for (Method m : methods) {
				if (m.isAnnotationPresent(FillItem.class)) {
					Class[] paramTypes = m.getParameterTypes();
					if(paramTypes!=null && paramTypes.length == 1 && paramTypes[0].equals(TableInfo.class))
					{
						String fillItemName=m.getAnnotation(FillItem.class).itemName(); 
						Object result = m.invoke(element,tableInfo);
						file.replaceTxtByStr(fillItemName, result.toString());
					}
					else if(paramTypes!=null && paramTypes.length == 2 
							&& paramTypes[0].equals(CodeModel.class)
							&& paramTypes[1].equals(TableInfo.class))
					{
						String fillItemName=m.getAnnotation(FillItem.class).itemName(); 
						Object result = m.invoke(element,codeModel,tableInfo);
						file.replaceTxtByStr(fillItemName, result.toString());
					}
				}
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	@FillItem(itemName = "<##TIME##>")
	public String fillItem_TIME(TableInfo tableInfo)
	{
		return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
	}
	
//	@FillItem(itemName = "<##PRJ_ID##>")
//	public String PRJ_ID(TableInfo tableInfo)
//	{
//		return GlobalInfo.PRJ_NAME.toLowerCase();
//	}
	
	
	
	protected boolean isCopySus(CodeModel codeModel,TableInfo tableInfo)
	{
		String modelName= this.getClass().getSimpleName()+".scd";
		String modelFilePath=this.getClass().getResource("").getPath();
		
		try {
			modelFilePath = java.net.URLDecoder.decode(modelFilePath,"utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		file= new FileUtil(codeModel.getMainPath()+this.getFilePath(tableInfo),this.getFileName(tableInfo));
		if(file.copyToFile(modelFilePath+"/"+modelName)==false)
		{
			return false;
		}
		
		return true;
	}
	
}
